package com.njtoyo.taxi.admin.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.njtoyo.taxi.admin.mapper.master.entity.Company;
import com.njtoyo.taxi.admin.mapper.master.entity.IncomeBelongingLog;
import com.njtoyo.taxi.admin.mapper.master.mapper.CompanyMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.IncomeBelongingLogMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.RideOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 统计公司收益任务
 */
@Component
@Slf4j
public class CompanyIncomeTask {


    @Autowired
    private IncomeBelongingLogMapper incomeBelongingLogMapper;
    @Autowired
    private RideOrderMapper rideOrderMapper;
    @Autowired
    private CompanyMapper companyMapper;


    @Scheduled(cron = "0 0 3 * * ? ")
    public void companyIncome() {
        List<Company> companyList = companyMapper.selectList(null);
        if (CollUtil.isNotEmpty(companyList)) {
            List<Long> companyIds = companyList.stream().map(Company::getId).collect(Collectors.toList());
            Date startDate = DateUtil.beginOfDay(DateUtil.offsetDay(DateUtil.date(), -1));
            Date endDate = DateUtil.endOfDay(DateUtil.offsetDay(DateUtil.date(), -1));
            List<Map<String, Object>> result = rideOrderMapper.selectAmountByCompany(startDate, endDate, companyIds);

            for (Map<String, Object> map : result) {
                IncomeBelongingLog add = new IncomeBelongingLog();
                add.setCompanyId(MapUtil.getLong(map, "companyId"));
                add.setCompanyEarning(MapUtil.get(map, "amount", BigDecimal.class));
                add.setTaskTime(DateUtil.formatDate(DateUtil.offsetDay(DateUtil.date(), -1)));
                add.setCreatedAt(DateUtil.date());
                incomeBelongingLogMapper.insert(add);
            }

        }
    }
}
